package com.warm.androidstudy.utils;

import java.text.DecimalFormat;

public class NumberUtils {
    /**
     * double保留2位小数 并去除多余的0
     */
    public static String doubleAdjustment(double number) {
        return subZeroAndDot(new DecimalFormat("0.00").format(number)).replace(",", ".");
    }

    /**
     * double保留3位小数 并去除多余的0
     */
    public static String doubleAdjustment3(double number) {
        return subZeroAndDot(new DecimalFormat("0.000").format(number)).replace(",", ".");
    }

    /**
     * double保留1位小数 并去除多余的0
     */
    public static String doubleAdjustment1(double number) {
        return subZeroAndDot(new DecimalFormat("0.0").format(number)).replace(",", ".");
    }

    /**
     * double保留2为小数
     */
    public static String doubleAdjustment2(double number) {
        return new DecimalFormat("0.00").format(number).replace(",", ".");
    }

    /**
     * 使用java正则表达式去掉多余的.与0
     *
     * @param s
     * @return
     */
    public static String subZeroAndDot(String s) {
        if (s.indexOf(".") > 0) {
            s = s.replaceAll("0+?$", "");// 去掉多余的0
            s = s.replaceAll("[.]$", "");// 如最后一位是.则去掉
        }
        return s;
    }

    public static String getDistance(String distance) {
        double distances;
        try {
            distances = Double.valueOf(distance);
        } catch (Exception e) {
            return distance;
        }
        if (distances > (double) 1000) {
            return doubleAdjustment(distances / 1000) + "km";
        } else {
            return doubleAdjustment(distances) + "m";
        }
    }

    public static String getConsumeCalories(double calories) {
        if (calories < 1) {
            return doubleAdjustment2(calories*1000d);
        } else {
            return doubleAdjustment2(calories );
        }
    }

    public static String getConsumeCaloriesUnit(double calories) {
        if (calories < 1) {
            return "Cal";
        } else {
            return "kCal";
        }
    }

    public static String getTime(long time) {
        if (time < 1000) {
            return time + "";
        } else if (time < 60 * 1000) {
            return doubleAdjustment(time / 1000f);
        } else if (time < 60 * 60 * 1000) {
            return time / 60 / 1000 + "";
        } else
            return time / 60 / 60 / 1000 + "";
    }

    public static float getTimes(long time) {
        if (time < 1000) {
            return time;
        } else if (time < 60 * 1000) {
            return time / 1000f;
        } else if (time < 60 * 60 * 1000) {
            return time / 60f / 1000f;
        } else
            return time / 60f / 60f / 1000f;
    }

    public static String getUnit(long time) {
        if (time < 1000) {
            return "ms";
        } else if (time < 60 * 1000) {
            return "s";
        } else if (time < 60 * 60 * 1000) {
            return "min";
        } else
            return "h";
    }
}
